(function($) {

	$.extend({
		'dialog' : {
			'me' : function() {
				return $('#' + $.dialog.defaults.id);
			},
			'getForm' : function(dialogButton) {
				return $(dialogButton == undefined ? this : dialogButton).parent().closest('.window').find('form');
			},
			'getGrid' : function(dialogButton) {
				return $(dialogButton == undefined ? this : dialogButton).parent().closest('.window').find('.datagrid-f');
			},
			'open' : function(opt) {
				var options = $.extend({}, $.dialog.defaults, opt);
				if (options.center == true) {
					var left = $(document).width() - options.width < 0 ? 0 : ($(document).width() - options.width) / 2;
					var top = $(document).height() - options.height < 0 ? 0 : ($(document).height() - options.height) / 2;
					options = $.extend({}, options, {
						left : left,
						top : top,
						closed: false
					});
				}
				$.dialog.me().dialog(options);
			},
			'close' : function() {
				$.dialog.me().dialog('close');
			},
			'refresh' : function() {
				$.dialog.me().dialog('refresh');
			},
			'reset' : function() {
				$.dialog.getForm(this).form('reset');
			},
			'submit' : function() {
				var options = $.dialog.me().data('dialog').options;
				$.ajaxform.submit.call(this, options);
			},
			'getFormJson' : function(dialogButton) {
				var $form = $.dialog.getForm(dialogButton == undefined ? this : dialogButton);
				var params = $form.serializeArray();
				var opts = {};
				$.each(params, function() {
					if (this.value !== '') {
						if (opts[this.name] !== undefined) {
							if (!opts[this.name].push) {
								opts[this.name] = [ opts[this.name] ];
							}
							opts[this.name].push(this.value);
						} else {
							opts[this.name] = this.value;
						}
					}
				});
				return opts;
			}
		}
	});

	$.extend($.dialog, {
		'defaults' : {
			id : 'dialog',
			title : '新窗口',
			href : null,
			modal : true,
			width : 400,
			height : 200,
			resizable : true,
			buttons : null,
			center : true,
			onBeforeSubmit : function(options) {
			},
			onSubmitSuccess : function(data, options) {
			},
			tools : [ {
				iconCls : 'icon-reload',
				handler : $.dialog.refresh
			} ],
		},
		'buttons' : {
			'reset' : {
				text : '重置',
				iconCls : 'icon-reload',
				handler : $.dialog.reset
			},
			'save' : {
				text : '保存',
				iconCls : 'icon-ok',
				handler : $.dialog.submit
			},
			'close' : {
				text : '关闭',
				iconCls : 'icon-stop',
				handler : function() {
					$.dialog.me().dialog('close');
				}
			},
			'search' : {
				text : '查询',
				iconCls : 'icon-search',
				handler : function() {
					var options = $.dialog.me().dialog('options');
					var $form = $.dialog.getForm(this);
					$form.enableDisable();
					$form.disableEmpty();
					$.crudgrid.gridMethod(options.grid, 'load', $.ajaxform.buildQueryParam($form.serializeArray()));
				}
			}
		}
	});
})(jQuery);
